package tools

import (
	"archive/zip"
	"io"
	"os"
	"path/filepath"
)

func Unzip(zipFile, destDir string) ([]string, error) {
	var fileNames []string
	r, err := zip.OpenReader(zipFile)
	if err != nil {
		return fileNames, err
	}
	defer r.Close()

	for _, f := range r.File {
		fpath := filepath.Join(destDir, f.Name)
		if f.FileInfo().IsDir() {
			os.MkdirAll(fpath, os.ModePerm)
		} else {
			if err = os.MkdirAll(filepath.Dir(fpath), os.ModePerm); err != nil {
				return fileNames, err
			}
			outFile, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
			if err != nil {
				return fileNames, err
			}
			rc, err := f.Open()
			if err != nil {
				outFile.Close()
				return fileNames, err
			}
			_, err = io.Copy(outFile, rc)

			outFile.Close()
			rc.Close()
			if err != nil {
				return fileNames, err
			}
			fileNames = append(fileNames, fpath)
		}
	}
	return fileNames, nil
}
